package com.yxym.synchronized_;

//模拟线程死锁
public class DeadLock_ {
    public static void main(String[] args) {
        //模拟线程死锁现象
        DeadLockDemo deadLockDemo1 = new DeadLockDemo(true);
        deadLockDemo1.setName("A线程...");
        deadLockDemo1.start();
        DeadLockDemo deadLockDemo2 = new DeadLockDemo(true);
        deadLockDemo2.setName("B线程...");
        deadLockDemo2.start();
    }
}
class DeadLockDemo extends Thread{
    static Object object1 = new Object();//保证多线程，共享一个对象static
    static Object object2 = new Object();
    boolean flag;

    public DeadLockDemo(boolean flag){
        this.flag = flag;
    }

    @Override
    public void run() {
        /***
         *
         */
        if(flag){
            synchronized (object1){//对象互斥锁，下面为互斥代码
                System.out.println(Thread.currentThread().getName() + "进入1");
                synchronized (object2){
                    System.out.println(Thread.currentThread().getName() + "进入2");
                }
            }
        }else {
            synchronized (object2){//对象互斥锁，下面为互斥代码
                System.out.println(Thread.currentThread().getName() + "进入3");
                synchronized (object1){
                    System.out.println(Thread.currentThread().getName() + "进入4");
                }
            }
        }
    }
}